package com.engine.jz.util;

import cn.hutool.http.Header;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import weaver.general.BaseBean;

import java.lang.reflect.Type;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.HashMap;
import java.util.Map;

/**
 * @version 1.0
 * @Title ecology-9
 * @Company 泛微软件
 * @CreateDate 2024/11/26
 * @Description 旷视工具类
 * @Author AdminZm
 */
public class KsUtils {

    BaseBean baseBean = new BaseBean();

    /**
     * 登陆鉴权挑战
     */
    public String loginChallenge(String username, String ip) {
        String result = null;
        try {
            String url = "http://" + ip + "/api/auth/login/challenge?username=" + username;
            HttpGet httpGet = new HttpGet(url);
            CloseableHttpClient httpClient = HttpClients.createDefault();
            CloseableHttpResponse response = httpClient.execute(httpGet);
            return CommonUtil.getString(response);
        } catch (Exception e) {
            baseBean.writeLog("loginChallenge error:" + e);
        }
        return result;
    }

    /**
     * 设备登陆
     */
    public String login(String session_id, String challenge, String salt, String ip) {
        String result = null;
        baseBean.writeLog("login start.");
        try {
            String pwd = baseBean.getPropValue("jzjg_zm_prop", "ks_pwd");
            // 获取SHA-256 MessageDigest实例
            MessageDigest digest = MessageDigest.getInstance("SHA-256");

            // 将输入字符串转换为字节数组，并更新到digest中
            // 注意：这里简单地将字符串拼接起来，但在实际应用中可能需要更复杂的组合方式
            String input = pwd + salt + challenge;
            digest.update(input.getBytes(StandardCharsets.UTF_8));

            // 计算哈希值
            byte[] hash = digest.digest();

            // 将字节数组转换为十六进制字符串
            StringBuilder hexString = new StringBuilder();
            for (byte b : hash) {
                String hex = Integer.toHexString(0xff & b);
                if (hex.length() == 1) hexString.append('0');
                hexString.append(hex);
            }

            Map<String, Object> paramMap = new HashMap<>();
            paramMap.put("session_id", session_id);
            paramMap.put("username", "admin");
            paramMap.put("password", hexString);
            String url = "http://" + ip + "/api/auth/login?type=other";
            result = HttpRequest.post(url)
                    .header(Header.CONTENT_TYPE, "application/json")
                    .body(JSONObject.toJSONString(paramMap))
                    .timeout(20000)
                    .execute().body();
            baseBean.writeLog("login end.");
            return result;
        } catch (Exception e) {
            baseBean.writeLog("login error:" + e);
        }
        return result;
    }

    /**
     * 设备登出
     */
    public String logout(String sessionId, String ip) {
        String result = null;
        try {
            String url = "http://" + ip + "/api/auth/logout";
            HttpGet httpGet = new HttpGet(url);
            httpGet.addHeader("Cookie", "sessionID=" + sessionId);
            CloseableHttpClient httpClient = HttpClients.createDefault();
            CloseableHttpResponse response = httpClient.execute(httpGet);
            return CommonUtil.getString(response);
        } catch (Exception e) {
            baseBean.writeLog("logout error:" + e);
        }
        return result;
    }

    /**
     * 条件查询通行记录
     */
    public String queryMj(String session_id, Map<String, Object> paramMap, String ip) {
        String result = null;
        baseBean.writeLog("queryMj start.");
        try {
            String url = "http://" + ip + "/api/passes/query";
            result = HttpRequest.post(url)
                    .header(Header.CONTENT_TYPE, "application/json")
                    .header(Header.COOKIE, "sessionID=" + session_id)
                    .body(JSONObject.toJSONString(paramMap))
                    .timeout(20000)
                    .execute().body();
            baseBean.writeLog("queryMj end.");
            return result;
        } catch (Exception e) {
            baseBean.writeLog("queryMj error:" + e);
        }
        return result;
    }

    /**
     * 条件查询人员信息
     */
    public String queryHrm(String session_id, Map<String, Object> paramMap, String ip) {
        String result = null;
        baseBean.writeLog("queryHrm start.");
        try {
            String url = "http://" + ip + "/api/persons/query";
            result = HttpRequest.post(url)
                    .header(Header.CONTENT_TYPE, "application/json")
                    .header(Header.COOKIE, "sessionID=" + session_id)
                    .body(JSONObject.toJSONString(paramMap))
                    .timeout(20000)
                    .execute().body();
            baseBean.writeLog("queryHrm end.");
            return result;
        } catch (Exception e) {
            baseBean.writeLog("queryHrm error:" + e);
        }
        return result;
    }

    /**
     * 获取指定id的人员信息
     */
    public String queryHrmById(String session_id, String ip, String ryId) {
        String result = null;
        baseBean.writeLog("queryHrmById start.");
        try {
            String url = "http://" + ip + "/api/persons/item/" + ryId;
            result = HttpRequest.get(url)
                    .header(Header.CONTENT_TYPE, "application/json")
                    .header(Header.COOKIE, "sessionID=" + session_id)
                    .timeout(20000)
                    .execute().body();
            baseBean.writeLog("queryHrmById end.");
            return result;
        } catch (Exception e) {
            baseBean.writeLog("queryHrmById error:" + e);
        }
        return result;
    }

    /**
     * 创建人员信息
     */
    public String createHrm(String session_id, Map<String, Object> paramMap, String ip) {
        String result = null;
        baseBean.writeLog("createHrm start.");
        try {
            String url = "http://" + ip + "/api/persons/item";
            result = HttpRequest.post(url)
                    .header(Header.CONTENT_TYPE, "application/json")
                    .header(Header.COOKIE, "sessionID=" + session_id)
                    .body(JSONObject.toJSONString(paramMap))
                    .timeout(20000)
                    .execute().body();
            baseBean.writeLog("createHrm end.");
            return result;
        } catch (Exception e) {
            baseBean.writeLog("createHrm error:" + e);
        }
        return result;
    }

    /**
     * 设置人员信息
     */
    public String updateHrm(String session_id, Map<String, Object> paramMap, String rygh, String ip) {
        String result = null;
        baseBean.writeLog("updateHrm start.");
        try {
            String url = "http://" + ip + "/api/persons/item/" + rygh;
            result = HttpRequest.put(url)
                    .header(Header.CONTENT_TYPE, "application/json")
                    .header(Header.COOKIE, "sessionID=" + session_id)
                    .body(JSONObject.toJSONString(paramMap))
                    .timeout(20000)
                    .execute().body();
            baseBean.writeLog("updateHrm end.");
            return result;
        } catch (Exception e) {
            baseBean.writeLog("updateHrm error:" + e);
        }
        return result;
    }

    /**
     * 删除人员信息
     */
    public String delHrm(String session_id, String rygh, String ip) {
        String result = null;
        baseBean.writeLog("delHrm start.");
        try {
            String url = "http://" + ip + "/api/persons/item/" + rygh;
            result = HttpRequest.delete(url)
                    .header(Header.CONTENT_TYPE, "application/json")
                    .header(Header.COOKIE, "sessionID=" + session_id)
                    .timeout(20000)
                    .execute().body();
            baseBean.writeLog("delHrm end.");
            return result;
        } catch (Exception e) {
            baseBean.writeLog("delHrm error:" + e);
        }
        return result;
    }
}


